package com.julis.activity.obu_function;

import android.content.Context;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.excel.ExcelUtils;
import com.github.czy1121.view.RoundButton;
import com.julis.R;
import com.julis.adapter.TradeAdapter;
import com.julis.bean.ObuTrade_Info;
import com.julis.db.Z_TradeInfoDao;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 交易记录列表
 */

public class TradeRecord_List_Activity extends AppCompatActivity {

    @BindView(R.id.img_back)
    RelativeLayout imgBack;
    @BindView(R.id.layout_start)
    RelativeLayout layout_start;
    @BindView(R.id.layout_end)
    RelativeLayout layout_end;

    @BindView(R.id.recyclerView)
    RecyclerView mRvMain;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
    TradeAdapter mAdapter;
    Z_TradeInfoDao z_obuInfoDao;
    List<ObuTrade_Info> obu_infos;
    @BindView(R.id.bt_daochu)
    RoundButton btDaochu;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_startvalue)
    TextView tvStartvalue;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.tv_endvalue)
    TextView tvEndvalue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traderecord_list);
        ButterKnife.bind(this);
        z_obuInfoDao = new Z_TradeInfoDao(this);
        obu_infos = z_obuInfoDao.queryForAll();
        Collections.reverse(obu_infos);
// 设置布局
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRvMain.setLayoutManager(linearLayoutManager);
        mRvMain.addItemDecoration(
                new HorizontalDividerItemDecoration.Builder(this).build());
        mAdapter = new TradeAdapter(this);
        mRvMain.setAdapter(mAdapter);
        mAdapter.addItem(obu_infos);
        mAdapter.setOnItemClickListener(new TradeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                Toast.makeText(UIUtil.getContext(), "click" + position, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position) {
//                Toast.makeText(UIUtil.getContext(), "long click" + position, Toast.LENGTH_SHORT).show();
            }
        });
        initview();
        tvStartvalue.setText(getTimes(new Date()));
        tvEndvalue.setText(getTimes(new Date()));
        tvStartvalues = getTimes(new Date());
        tvendvalues = getTimes(new Date());
    }


    private String fileName;
    private ArrayList<ArrayList<String>> recordList;

    File file;
    private static String[] title = {"编号", "时间", "SN号", "MAC号", "结果", "检测时长", "备注"};

    /**
     * 导出excel
     *
     * @param
     */
    public void out_excel() {
        if (obu_infos2 != null && obu_infos2.size() > 0) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH_mm_ss");
            Date curDate = new Date(System.currentTimeMillis());
            String str = formatter.format(curDate);
            file = new File(getSDPath() + "/Record");
            makeDir(file);
            updata(this, file);
            ExcelUtils.initExcel(file.toString() + "/零元消费检测" + str + ".xls", title, this);
            fileName = getSDPath() + "/Record/零元消费检测" + str + ".xls";
            ExcelUtils.writeObjListToExcel(getRecordData(), fileName, this);
        } else {
            Toast.makeText(this, "暂无数据，请重新选择！", Toast.LENGTH_SHORT).show();
        }


    }

    public static void updata(Context context, File file) {
        MediaScannerConnection.scanFile(context,
                new String[]{file.getAbsolutePath()}, null, null);
    }

    /**
     * 将数据集合 转化成ArrayList<ArrayList<String>>
     *
     * @return
     */
    private ArrayList<ArrayList<String>> getRecordData() {
        recordList = new ArrayList<>();
        for (int i = 0; i < obu_infos2.size(); i++) {
            ObuTrade_Info obuTradeInfo = obu_infos2.get(i);
            ArrayList<String> beanList = new ArrayList<String>();
            beanList.add("" + (i + 1));
            beanList.add(obuTradeInfo.getChecktime());
            beanList.add(obuTradeInfo.getSn());
            beanList.add(obuTradeInfo.getMac());
            beanList.add(obuTradeInfo.getResults());
            beanList.add(obuTradeInfo.getTimelong());
            beanList.add(obuTradeInfo.getRemarks());
            recordList.add(beanList);
        }
        return recordList;

    }


    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        String dir = sdDir.toString();
        return dir;
    }

    public void makeDir(File dir) {
        if (!dir.getParentFile().exists()) {
            makeDir(dir.getParentFile());
        }
        dir.mkdir();
    }

    String type = "1";

    @OnClick({R.id.img_back, R.id.bt_daochu, R.id.layout_start, R.id.layout_end})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.bt_daochu:
                if (TextUtils.isEmpty(tvStartvalues)) {
                    Toast.makeText(TradeRecord_List_Activity.this, "请选择开始时间", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(tvStartvalues)) {
                    Toast.makeText(TradeRecord_List_Activity.this, "请选择结束时间", Toast.LENGTH_SHORT).show();

                    return;
                }
                int i = compare_date(tvStartvalues, tvendvalues);
                if (i < 0) {
                    Toast.makeText(TradeRecord_List_Activity.this, "结束时间不能早于开始时间", Toast.LENGTH_SHORT).show();
                    return;
                }
                obu_infos2 = z_obuInfoDao.query(tvStartvalues, tvendvalues);
                out_excel();
                break;
            case R.id.layout_start:
                type = "1";
                pvTime.show(tvStart);

                break;
            case R.id.layout_end:
                type = "2";
                pvTime.show(tvStart);

                break;

        }
    }


    TimePickerView pvTime;
    List<ObuTrade_Info> obu_infos2;
    String tvStartvalues = "";
    String tvendvalues = "";

    void initview() {


        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2013, 0, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2029, 11, 28);
        //时间选择器
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                String times = getTimes(date);
                Log.e("ZZZ", "xx" + times);
                if (type.equals("1")) {
                    tvStartvalue.setText(times);
                    tvStartvalues = times;
                } else {
                    tvEndvalue.setText(times);
                    tvendvalues = times;
                }

            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(true)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();
    }


    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }

    public static int compare_date(String DATE1, String DATE2) {


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }
}
